
from rest_framework import generics
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet

from apps.meiduo_admin.serializers.orders_serializers import OrderSeriazlier, OrderSmpileSeriazlier
from apps.meiduo_admin.utils.pagenum import PageNum
from apps.orders.models import OrderInfo

class OrdersView(ModelViewSet):
    # # 指定使用的序列化器
    # serializer_class = OrderSeriazlier
    # 指定分页器
    pagination_class = PageNum
    # queryset = OrderInfo.objects.all().order_by("create_time")
    # 用方法给查询级加条件限制
    def get_queryset(self):
        # 从查询参数中获取数据
        keyword = self.request.query_params.get("keyword")
        queryset = OrderInfo.objects
        if keyword:
            queryset = queryset.filter(order_id__contains=keyword)
        queryset = queryset.order_by("-create_time")
        return queryset
    # 用方法指定序列化器
    def get_serializer_class(self):
        # list======>ordersimpleserializer
        # retrieve====>orderserializer
        # 视图集有一个属性self.action  当前请求要执行的方法名称
        if self.action=="list":
            return OrderSmpileSeriazlier
        elif self.action=="retrieve":
            return OrderSeriazlier
    # 添加装饰器到查询集里面   detail=True可以自动生成带参数的路由
    # detail=False  不能生成待参数的路由
    @action(methods=['put'], detail=True)
    # 修改指定订单状态
    def status(self,request,pk):
        # 获取订单对象   get_object封装了根据主键查询对象的代码
        order = self.get_object()
        # 获取要修改的状态值
        status = request.data.get('status')
        # 修改订单状态
        order.status = status
        order.save()
        # # 返回结果
        # ser = self.get_serializer(order)
        return Response({'order_id': order.order_id,'status': status })
